﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;

namespace ProjBackEnd.Lib
{
    public class WebUtil
    {
        public static string GetMethod(string _strUrl, string _strPara)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_strUrl + (_strPara == "" ? "" : "?") + _strPara);
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "text/html;charset=UTF-8";
            httpWebRequest.Timeout = 5000;
            string strRet = "";
            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                strRet = streamReader.ReadToEnd();
                httpWebResponse.Close();
                streamReader.Close();
            }
            catch (Exception ex)
            {
                strRet = "";
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
            }
            return strRet;
        }

        public static string PostMethod(string _strUrl, string _strPara, int _iTimeOut = 10, string _strToken = "")
        {
            string strReturn = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_strUrl);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                byte[] uploadBody = Encoding.UTF8.GetBytes(_strPara);
                request.ContentLength = uploadBody.Length;
                request.Timeout = _iTimeOut * 1000;
                if (!string.IsNullOrEmpty(_strToken)) request.Headers.Add("token", _strToken);

                Stream smRequest = request.GetRequestStream();
                smRequest.Write(uploadBody, 0, uploadBody.Length);
                smRequest.Close();
                HttpWebResponse hwResponse = (HttpWebResponse)request.GetResponse();
                Stream smResponse = hwResponse.GetResponseStream();

                StreamReader smReader = new StreamReader(smResponse, Encoding.UTF8);
                strReturn = smReader.ReadToEnd().Trim();
                smReader.Close();
            }
            catch (Exception ex) { strReturn = ex.Message; }
            return strReturn;
        }
    }
}